package com.prize.service.impl;

import com.prize.config.RedisConfig;
import com.prize.dtos.ResponseResult;
import com.prize.enums.CodeEnum;
import com.prize.service.LoginService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

/**
 * @descriptions: 登录
 * @author: yunqiang
 * @date: 2022/5/28 16:07
 */
@Service
public class LoginServiceImpl implements LoginService {

    @Resource
    private RedisConfig redisConfig;

    //用户登录错误次数
    public final static String USERLOGINTIMES = "user_login_times_";

    /***
     * @param username 用户名
     * @param password 密码
     * @param uuid uuid
     * @param captcha 验证码
     * @return
     */
    @Override
    public ResponseResult login(String username, String password, String uuid, String captcha) {
        //用户错误登录次数校验
        Object object = redisConfig.getRedisTemplateByDb(1).opsForValue().get(USERLOGINTIMES + username);
        if (object != null) {
            Integer errortimes = Integer.valueOf(String.valueOf(object));
            if (errortimes != null && errortimes >= 5) {
                return ResponseResult.error(CodeEnum.USER_NOT_PASSWORD.getCode(), CodeEnum.USER_NOT_PASSWORD.getErrorMessage());
            }
        }
        //查询验证码
        String ct = String.valueOf(redisConfig.getRedisTemplateByDb(1).opsForValue().get(uuid));
        if (StringUtils.isBlank(captcha)) {
            return ResponseResult.error(CodeEnum.ERROR_CAPTCHA.getCode(), CodeEnum.ERROR_CAPTCHA.getErrorMessage());
        }
        if (StringUtils.isBlank(captcha) || !captcha.equalsIgnoreCase(captcha)) {
            return ResponseResult.error(CodeEnum.ERROR_CAPTCHA.getCode(), CodeEnum.ERROR_CAPTCHA.getErrorMessage());
        }
        //根据用户名密码查询用户是否存在
        if(username.equals("admin") && password.equals("123456")){
            return ResponseResult.success();
        }
        return ResponseResult.error(CodeEnum.USER_NOT_AUTH.getCode(), CodeEnum.USER_NOT_AUTH.getErrorMessage());
    }
}
